package com.sysu.homework.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.sysu.homework.model.Homework;
import com.sysu.homework.model.HomeworkResult;
import com.sysu.homework.model.Student;
import com.sysu.homework.service.HomeworkResultService;
import com.sysu.homework.service.HomeworkService;
import com.sysu.homework.service.StudentService;

@Component("homeworkResultAction")
@Scope("prototype")
public class HomeworkResultAction extends ActionSupport{
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	private String savePath;
	private int homeworkid;
	
	private StudentService studentService;
	private HomeworkResultService homeworkResultService;
	private HomeworkService homeworkService;
	private HttpSession session = null;
	private String role ;
	private List<HomeworkResult> myResults = new ArrayList<HomeworkResult>();
	private List<HomeworkResult> myGroupResults = new ArrayList<HomeworkResult>();
	private List<HomeworkResult> allResults = new ArrayList<HomeworkResult>();
	private String filename;
	private InputStream targetFile;
	
	
	@Override
	public String execute() throws Exception {
		int userid=(Integer)session.getAttribute("user");
		String filetype = getUploadFileName().split("\\.")[1];
		String filename = userid+"_"+homeworkid+"."+filetype;
		System.out.println(filename);
		
		HomeworkResult result = new HomeworkResult();
		result.setFilename(filename);
		result.setTitle(getUploadFileName());
		Student student = studentService.getStudentById(userid);
		result.setStudent(student);
		
		Homework homework = homeworkService.getHomeworkById(homeworkid);
		result.setHomework(homework);
		
		HomeworkResult hwResult = homeworkResultService.getHomeworkResultByFilename(filename);
		if (hwResult!=null){
			int _id = hwResult.getId();
			result.setId(_id);
		}
		
		if(homeworkResultService.saveOrUpdate(result)>0){
			writeToBasePath(filename);
			String realPath = ServletActionContext.getServletContext().getRealPath("/");
			String targetPath = realPath+"\\";   //文件解压后的路径
	        String zipFile = getSavePath()+"\\"+filename;  //文件的尽对路径
	        unzipFile(targetPath, zipFile);  
			return "success";
		}
		
		return null;
		
	}
	private void writeToBasePath(String filename ) throws Exception{
		FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+filename);
		FileInputStream fis = new FileInputStream(getUpload());
		System.out.println("文件名"+uploadFileName);
		System.out.println("文件类型"+uploadContentType);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer))>0)
		{
			fos.write(buffer, 0, len);
		}
		
	}
	
	
	public void unzipFile(String targetPath, String zipFilePath) {  
        try {  
            File zipFile = new File(zipFilePath);  
            InputStream is = new FileInputStream(zipFile);  
            ZipInputStream zis = new ZipInputStream(is);  
            ZipEntry entry = null;  
            System.out.println("开始解压:" + zipFile.getName() + "...");  
            
           while ((entry = zis.getNextEntry()) != null) {  
                String zipPath = entry.getName(); 
                System.out.println("entry.getName() = "+entry.getName());
               try {  
                    if (entry.isDirectory()) 
                    {  
                        File zipFolder = new File(targetPath + File.separator  
                                + zipPath);  
                        if (!zipFolder.exists()) {  
                            zipFolder.mkdirs();  
                        }  
                    } 
                    else 
                    {  
                       File file = new File(targetPath + File.separator  
                               + zipPath); 
                      System.out.println( file.getName());
                        if (!file.exists()) {  
                            File pathDir = file.getParentFile();  
                           pathDir.mkdirs();  
                           file.createNewFile();  
                       }  

                      FileOutputStream fos = new FileOutputStream(file);  
                        int bread;  
                        while ((bread = zis.read()) != -1) {  
                           fos.write(bread);  
                        }  
                        fos.close();  
  
                    }  
                   System.out.println("成功解压:" + zipPath);  
  
                } catch (Exception e) {  
                    System.out.println("解压" + zipPath + "失败");  
                  continue;  
                }  
            }  
            zis.close();  
            is.close();  
           System.out.println("解压结束");  
        } catch (Exception e) {  
           e.printStackTrace();  
        }  
  
    }  
	
	public String showHomeworkResults() {
		int userid = (Integer)session.getAttribute("user");
		role = session.getAttribute("role").toString();
		if(role.equals("student")){
			myResults = homeworkResultService.getMyHomeworkResults(userid);
			myGroupResults = homeworkResultService.getMyGroupHomeworkResults(userid);
		}
		allResults = homeworkResultService.getAllHomeworkResults();
		return "show";
	}
	
	public InputStream getTargetFile() throws Exception{
		
		FileInputStream input = null;
		  try {
		   String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload/"+getFilename());  
		   input = new FileInputStream (realPath);
		  }catch(Exception e) {
		   e.printStackTrace();
		  }
		  return input;
	}
	public String download() throws Exception{
		targetFile = getTargetFile();
		filename = getFilename();
		return "download";
	}
	
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath("/WEB-INF/"+savePath);
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	public void setHomeworkid(int homeworkid) {
		this.homeworkid = homeworkid;
	}
	public int getHomeworkid() {
		return homeworkid;
	}
	@Resource
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}
	public StudentService getStudentService() {
		return studentService;
	}
	
	@Resource
	public void setHomeworkResultService(HomeworkResultService homeworkResultService) {
		this.homeworkResultService = homeworkResultService;
	}
	public HomeworkResultService getHomeworkResultService() {
		return homeworkResultService;
	}
	
	
	public HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public List<HomeworkResult> getMyResults() {
		return myResults;
	}
	public void setMyResults(List<HomeworkResult> myResults) {
		this.myResults = myResults;
	}
	public HomeworkResultAction() {
		session = ServletActionContext.getRequest().getSession();
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public void setTargetFile(InputStream targetFile) {
		this.targetFile = targetFile;
	}
	public void setMyGroupResults(List<HomeworkResult> myGroupResults) {
		this.myGroupResults = myGroupResults;
	}
	public List<HomeworkResult> getMyGroupResults() {
		return myGroupResults;
	}
	public void setAllResults(List<HomeworkResult> allResults) {
		this.allResults = allResults;
	}
	public List<HomeworkResult> getAllResults() {
		return allResults;
	}
	
	@Resource
	public void setHomeworkService(HomeworkService homeworkService) {
		this.homeworkService = homeworkService;
	}
	public HomeworkService getHomeworkService() {
		return homeworkService;
	}

}
